<template>
  <v-card title="序号+关系线+合并">
    <v-alert type="info" class="mb-10">
      <div slot="message">
        <div>
          借用工具方法
          <span class="blue-text"> handleSeqLine，colMergeCells </span> 实现
        </div>
      </div>
    </v-alert>

    <vcu-table
      ref="xTable"
      border
      :loadOptions="options"
      :spanLineMethod="spanLineMethod"
      :checkbox-config="{ checkField: 'checked', highlight: true }"
      @onPageLoad="onPageLoad"
    >
    </vcu-table>

    <div>总计： {{ total }}</div>
  </v-card>
</template>
<script>
import XEUtils from "xe-utils";
/**
 * @description 处理表格序号+关系线
 * @param seq {Boolean} 是否要处理序号
 * @param seqColumnName {String} 序号列名
 * @param rows {Array} 表格数据
 * @param line {Boolean} 是否要处理关系线
 * @param conditionColumnName {String} 判断条件列名（由后端告知）
 */
const handleSeqLine = ({
  seq = true,
  seqColumnName = "SEQ000",
  rows = null,
  line = true,
  conditionColumnName = "",
}) => {
  try {
    return new Promise((resolve, reject) => {
      if (!rows || conditionColumnName == "") {
        console.error("数据或条件不能为空");
        resolve(false);
      } else {
        if (!rows.length) resolve(false);
        let seqNum = 1;
        let _rows = {};
        let newRows = [];
        XEUtils.arrayEach(rows, (row) => {
          if (_rows[row[conditionColumnName]]) {
            _rows[row[conditionColumnName]].push(row);
          } else {
            _rows[row[conditionColumnName]] = [row];
          }
        });
        XEUtils.objectEach(_rows, (item, key) => {
          XEUtils.arrayEach(item, (m, i) => {
            if (seq) m[seqColumnName] = seqNum;
            if (line) {
              if (item.length > 1) {
                if (i == 0) {
                  m.spanLineType = 1;
                } else if (!item[i + 1]) {
                  m.spanLineType = 3;
                } else {
                  m.spanLineType = 2;
                }
              } else {
                m.spanLineType = 0;
              }
            }
            newRows.push(m);
          });
          seqNum++;
        });
        resolve({ total: seqNum - 1, rows: newRows });
      }
    });
  } catch (err) {
    return false;
  }
};

const colMergeCells = ({
  datas = [],
  columns = [],
  fields = [],
  type = true,
  conditionColumnName = "",
}) => {
  if (type) {
    //新方案
    if (datas.length && columns.length && fields.length) {
      let mergeCells = [];
      let _fields = [];
      const mergeCellsFun = (rowIndex, index, num) => {
        mergeCells.push({
          row: rowIndex,
          col: index,
          rowspan: num,
          colspan: 1,
        });
      };
      XEUtils.arrayEach(columns, (item, index) => {
        if (
          XEUtils.findLastIndexOf(
            fields,
            (fieldItem) => fieldItem === item.property
          ) > -1
        ) {
          _fields.push({
            property: item.property,
            index,
          });
        }
      });
      XEUtils.arrayEach(_fields, (field, fieldIndex) => {
        let num = 1;
        let rowIndex = 0;
        XEUtils.arrayEach(datas, (data, dataIndex) => {
          if (datas[dataIndex + 1]) {
            const handleMerge = () => {
              mergeCellsFun(rowIndex, field.index, num);
              rowIndex = dataIndex + 1;
              num = 1;
            };
            if (data[field.property] === datas[dataIndex + 1][field.property]) {
              if (conditionColumnName == "") {
                num++;
              } else {
                if (
                  data[conditionColumnName] ===
                  datas[dataIndex + 1][conditionColumnName]
                ) {
                  num++;
                } else {
                  handleMerge();
                }
              }
            } else {
              handleMerge();
            }
          } else {
            mergeCellsFun(rowIndex, field.index, num);
          }
        });
      });
      return mergeCells;
    } else {
      return [];
    }
  } else {
    //旧方案 （直接操作数据）
    if (datas.length) {
      let data = _.concat(datas, []);
      for (let j = 0; j < key.length; j++) {
        let num = 1;
        let RowSpan = `${key[j]}RowSpan`;
        let oldNum = 0;
        let oldIndex = [oldNum];
        let newIndex = [];

        for (let i = 0; i < data.length; i++) {
          if (data[i + 1] && data[i][key[j]] === data[i + 1][key[j]]) {
            num++;
          } else {
            newIndex.push(num);
            oldIndex.push((oldNum += num));
            num = 1;
          }
        }
        for (let i = 0; i < data.length; i++) {
          data[i][RowSpan] = 0;
        }
        for (let i = 0; i < oldIndex.length - 1; i++) {
          data[oldIndex[i]][RowSpan] = newIndex[i];
        }
      }
      return data;
    } else {
      return [];
    }
  }
};

export default {
  data() {
    return {
      options: {
        headUrl: "dataq/api/seqLineMergeHeader",
        pageUrl: "dataq/api/seqLineMergePage",
        checkbox: true,
      },
      total: 0,
    };
  },
  mounted() {},
  methods: {
    async onPageLoad({ datas }) {
      let res = await handleSeqLine({
        rows: datas,
        conditionColumnName: "id0000",
      });
      if (res) {
        this.total = res.total;
        await this.$refs.xTable.loadData(res.rows);
        this.handleMergeCells(res.rows);
      }
    },
    handleMergeCells(datas) {
      let _colMergeCells = colMergeCells({
        datas,
        columns: this.$refs.xTable.getColumns(),
        fields: ["SEQ000", "inputCode"],
        conditionColumnName: "id0000",
      });
      this.$refs.xTable.setMergeCells(_colMergeCells);
    },
    spanLineMethod({ column, row }) {
      if (column.property == "inHospWardName") {
        return row.spanLineType;
      }
      return false;
    },
  },
};
</script>

